import http from 'wechat-http'

// 封装请求根路径
http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = options => {
  const app = getApp()
  const header = { ...options.header }
  if (app.token && !options.url.includes('/refreshToken')) {
    header.Authorization = app.token
  }
  options.header = header
  return options
}

// 请求后拦截器
http.intercept.response = async res => {
  if (res.data.code === 401) {
    const app = getApp()
    const pageStack = getCurrentPages()
    const currentPage = pageStack[pageStack.length - 1]
    if (res.config.url.includes('/refreshToken')) {
      wx.redirectTo({
        url: `/pages/login/index?from=/${currentPage.route}`
      })
      return
    }
    // token 过期，刷新
    // 使用 refreshToken 获取新的 token
    if (!app.refreshToken) return
    const tokenData = await wx.$http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: app.refreshToken
      }
    })
    app.setToken('token', `Bearer ${tokenData.data.token}`)
    app.setToken('refreshToken', `Bearer ${tokenData.data.refreshToken}`)

    // 重新请求一下401接口
    // 让之前的接口与新参数合并，重新调用
    return wx.$http(
      Object.assign(res.config, {
        header: {
          Authorization: tokenData.data.token
        }
      })
    )
  }
  return res.data
}

// 挂载到全局
wx.$http = http

export default http
